package com.hrzyit.whistle.cases.ui.fragment

import android.app.Activity
import android.content.Context
import android.net.Uri
import android.os.Bundle
import android.os.Environment
import android.support.v7.widget.GridLayoutManager
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import com.bigkoo.alertview.AlertView
import com.bigkoo.alertview.OnItemClickListener
import com.bumptech.glide.Glide
import com.bumptech.glide.request.target.Target.SIZE_ORIGINAL
import com.hrzyit.base.common.BaseConstant
import com.hrzyit.base.ext.onClick
import com.hrzyit.base.ui.adapter.BaseRecyclerViewAdapter
import com.hrzyit.base.ui.fragment.BaseMvpFragment
import com.hrzyit.base.utils.AppPrefsUtils
import com.hrzyit.base.utils.DateUtils
import com.hrzyit.provider.common.ProviderConstant
import com.hrzyit.whistle.cases.R
import com.hrzyit.whistle.cases.data.bean.*
import com.hrzyit.whistle.cases.presenter.RegisterCasePresenter
import com.hrzyit.whistle.cases.presenter.view.RegisterCaseView
import com.hrzyit.whistle.cases.ui.adapter.ImageUploadViewAdapter
import com.jph.takephoto.app.TakePhoto
import com.jph.takephoto.app.TakePhotoImpl
import com.jph.takephoto.compress.CompressConfig
import com.jph.takephoto.model.TResult
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.interfaces.XPopupImageLoader
import com.tbruyelle.rxpermissions2.RxPermissions
import kotlinx.android.synthetic.main.fragment_register_case.*
import org.jetbrains.anko.support.v4.toast
import java.io.File


/**
 * 百度地图定位案件地址 Fragment
 * @author YangWei
 * @date 2019/4/11
 */
class RegisterCaseFragment : BaseMvpFragment<RegisterCasePresenter>(),
    RegisterCaseView, TakePhoto.TakeResultListener, View.OnClickListener {

    override fun injectComponent() {
    }

    override fun onCaseApplyResult(result: MutableMap<String,Any>) {
    }

    override fun onUploadResult(result: UploadInfo) {
    }

    override fun onGetSecondCategoryResult(t: MutableList<CategoryEntity>) {
    }

    override fun onGetOneCategoryResult(t: MutableList<CategoryEntity>) {
    }

    override fun onGetCaseQuestionTypeResult(t: MutableList<SysDictEntity>) {

    }

    override fun onGetCaseConditionListResult(t: MutableList<CategoryDetailsEntity>) {
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        super.onCreateView(inflater, container, savedInstanceState)
        // 加载 Fragment
        return inflater.inflate(R.layout.fragment_register_case, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        // 初始化权限
        mPermissions = RxPermissions(activity as Activity)

        // 初始化 TakePhoto
        mTakePhoto = TakePhotoImpl(this, this)
        mTakePhoto.onCreate(savedInstanceState)

        initView()

    }

    // 组件：拍照
    private lateinit var mTakePhoto: TakePhoto

    // 临时上传文件
    private lateinit var mTempFile: File

    // 权限控制组件
    private lateinit var mPermissions: RxPermissions

    // 新建案件实体：临时保存新建案件相关信息
    private lateinit var caseInfoEntity: CaseInfoEntity

    // 案件上传图片
    private lateinit var caseUploadInfoList: MutableList<UploadInfo>

    // 案件图片上传适配器
    private lateinit var imageUploadViewAdapter: ImageUploadViewAdapter

    /**
     * 初始化视图
     */
    private fun initView() {
// 初始化新建案件实体
        caseInfoEntity = CaseInfoEntity()
        caseInfoEntity.userId = AppPrefsUtils.getLong(BaseConstant.KEY_SP_USER_TOKEN)
        caseInfoEntity.toDept = AppPrefsUtils.getLong(ProviderConstant.KEY_SP_REPORT_DEPT_ID)
        caseInfoEntity.toDeptText = AppPrefsUtils.getString(ProviderConstant.KEY_SP_REPORT_DEPT_NAME)

        // 初始化案件图片上传组件的上传按钮
        caseUploadInfoList = mutableListOf()
        caseUploadInfoList.add(
            UploadInfo(
                null, null, BaseConstant.DEFAULT_UPLOAD_SERVER, null, null, null, null, 0, null
            )
        )


        // 类型、大类、小类、立案条件数据源
        // 案件问题类型
        mCaseQuestionCell.onClick(this)
        // 案件类型：大类
        mCaseOneSortCell.onClick(this)
        // 案件类型：小类
        mCaseSecondSortCell.onClick(this)
        // 案件立案条件
        mCaseConditionCell.onClick(this)

        // 案件上报单位
        mReportOrganizationCell.onClick(this)

        // 初始化上报单位
        mReportOrganizationCell.getRightView().text = this.caseInfoEntity.toDeptText

        // 案件地址及gps
        mCaseAddressGPSCell.onClick(this)

        // 上报按钮
        mReportBtn.onClick(this)

        // 案件去重按钮
        mRepeatBtn.onClick(this)

        // 上传文件组件

        val layoutManager = GridLayoutManager(context, 4)
        mCaseUploadImagesRv.layoutManager = layoutManager
        imageUploadViewAdapter = ImageUploadViewAdapter(context!!)
        mCaseUploadImagesRv.adapter = imageUploadViewAdapter
        imageUploadViewAdapter.setOnItemClickListener(object :
            BaseRecyclerViewAdapter.OnItemClickListener<UploadInfo> {
            override fun onItemClick(view: View, item: UploadInfo?, position: Int) {
                when (position + 1 == caseUploadInfoList.size) {
                    true -> {
                        // 弹出添加上传图片组件
                        showCaseAddImageAlertView()
                    }
                    false -> {
                        // 已上传的图片点击显示全图
                        showPhotoScreenView(view.findViewById(R.id.mCaseImageIv), item!!.imageUrl)
                    }
                }

            }

        })
    }

    /**
     * 显示图片全图
     */
    private fun showPhotoScreenView(imageView: ImageView, imageUrl: String) {
        XPopup.Builder(context)
            .asImageViewer(imageView, imageUrl, ImageLoader(context!!))
            .isShowSaveButton(false)
            .show()
    }

    class ImageLoader(val mContext : Context) : XPopupImageLoader {
        override fun loadImage(position: Int, uri: Any, imageView: ImageView) {
            Glide.with(mContext).load(uri as String).into(imageView)
//            GlideUtils.loadUrlImage(mContext, uri as String, imageView)
        }

        override fun getImageFile(context: Context, uri: Any): File {
            return Glide.with(context).load(uri).downloadOnly(SIZE_ORIGINAL, SIZE_ORIGINAL).get()
        }
    }

    /**
     * 弹出案件上传图片选择窗口
     */
    private fun showCaseAddImageAlertView() {
        AlertView(
            "上传照片",
            null,
            "取消",
            null,
            arrayOf("拍照", "从相册中选择"),
            context,
            AlertView.Style.ActionSheet,
            OnItemClickListener { _, position ->
                //                ActivityCompat.requestPermissions(
//                    this@RegisterCaseActivity,
//                    arrayOf("android.permission.CAMERA"),
//                    17
//                )

                // 照片压缩，每次都要调用否则只会执行一次
                val config = CompressConfig.ofDefaultConfig()

                // 压缩比 300k
                config.maxSize = 300 * 1024
                mTakePhoto.onEnableCompress(config, false)
                when (position) {
                    0 -> {
                        // 创建照片临时文件
                        createTempFile()
                        // 拍照
                        mTakePhoto.onPickFromCapture(Uri.fromFile(mTempFile))
                    }
                    1 -> {
                        mTakePhoto.onPickFromGallery()
                    }
                }
            }
        ).show()
    }

    // --- 回调
    override fun onClick(v: View?) {


    }

    override fun takeSuccess(result: TResult?) {
        val photo = result?.image?.compressPath
        Log.d("获取成功-未压缩", result?.image?.originalPath)
        Log.d("获取成功", photo)
    }

    override fun takeCancel() {
        toast("取消获取图片")
    }

    override fun takeFail(result: TResult?, msg: String?) {
        toast("获取图片失败")
    }

    /**
     * 创建上传图片临时文件
     */
    private fun createTempFile() {
        var tempFileName = "${DateUtils.curTime}.png"
        when (Environment.MEDIA_MOUNTED) {
            Environment.getExternalStorageState() -> {
                // 在存储卡中创建
                this.mTempFile = File(Environment.getExternalStorageDirectory(), tempFileName)
            }
            else -> {
                // 在内存中创建
                this.mTempFile = File(activity!!.filesDir, tempFileName)
            }
        }
    }
}